package com.example.wisdomclassroomapi.domain.service;

import com.example.wisdomclassroomapi.common.cache.RedisCache;
import com.example.wisdomclassroomapi.common.util.IdentificationUtil;
import com.google.code.kaptcha.Producer;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaDomainService {
    @Resource
    private Producer producer;
    @Resource
    private RedisCache cache;

    public void checkCaptcha(String captchaId, String captcha) {
        //校验验证码
        Object cacheObject = cache.getCacheObject(captchaId);
        if (Objects.isNull(cacheObject)) {
            throw new BadCredentialsException("验证码失效");
        }
        if (!StringUtils.equals(cacheObject.toString(), captcha)) {
            throw new BadCredentialsException("验证码错误");
        }
    }

    public Map<String, Object> createCaptcha(String captchaId) throws IOException {
        // 验证码生成
        String code = producer.createText();
        BufferedImage bi = producer.createImage(code);
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "jpg", fos);
        String img = Base64.encodeBase64String(fos.toByteArray());
        fos.close();

        // ID为空则生成随机ID
        if (StringUtil.isNullOrEmpty(captchaId)) {
            captchaId = IdentificationUtil.shortUuid();
        }

        // 将验证码code保存到缓存中
        cache.setCacheObject(captchaId, code, 60*10, TimeUnit.SECONDS);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("captchaId", captchaId);
        result.put("img", img);

        return result;
    }

    public String createCode(String captchaId) {
        // 验证码生成
        String code = producer.createText();
        // 将验证码code保存到缓存中
        cache.setCacheObject(captchaId, code, 60*10, TimeUnit.SECONDS);

        return code;
    }
}
